//package com.example.myapplication
//
//import android.os.Bundle
//import androidx.activity.enableEdgeToEdge
//import androidx.appcompat.app.AppCompatActivity
//import androidx.core.view.ViewCompat
//import androidx.core.view.WindowInsetsCompat
//// 1. 导入自动生成的 Binding 类
//import com.example.myapplication.databinding.ActivityMainBinding
//
//class MainActivity : AppCompatActivity() {
//    // 2. 声明一个 lateinit 的 Binding 变量
//    private lateinit var binding: ActivityMainBinding
//
//    override fun onCreate(savedInstanceState: Bundle?) {
//        super.onCreate(savedInstanceState)
//
//        // 3. 初始化 Binding 并设置布局
//        binding = ActivityMainBinding.inflate(layoutInflater)
//        setContentView(binding.root)
//
//        enableEdgeToEdge()
//        ViewCompat.setOnApplyWindowInsetsListener(binding.main) { v, insets -> // 注意：这里也通过 binding 访问 main
//            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
//            insets
//        }
//
//        // 4. 通过 binding 找到 Button 并设置点击事件
//        binding.button.setOnClickListener {
//            // 5. 通过 binding 找到 TextView 并修改其文本
//            binding.textView.text = resources.getString(R.string.clicked)
//        }
//    }
//}

package com.example.myapplication // 注意：这里的包名要和你项目的包名一致！

import android.os.Bundle
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet

class MainActivity : AppCompatActivity() {
    // 声明需要用到的控件
    private lateinit var rootLayout: ConstraintLayout
    private lateinit var ivFlag: ImageView
    private lateinit var tvHello: TextView
    private lateinit var btnClick: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 初始化根布局和所有控件
        initRootLayout()
        initFlagImageView()
        initHelloTextView()
        initClickButton()

        enableEdgeToEdge()
        setViewConstraints() // 应用新的布局约束
        handleWindowInsets()

        supportActionBar?.title = getString(R.string.app_name)
        setButtonClickListener()
        setFlagByLanguage()
    }

    private fun initRootLayout() {
        rootLayout = ConstraintLayout(this).apply {
            id = View.generateViewId()
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
            setBackgroundColor(resources.getColor(android.R.color.white, theme))
        }
        setContentView(rootLayout)
    }

    private fun initFlagImageView() {
        ivFlag = ImageView(this).apply {
            id = View.generateViewId()
            layoutParams = ConstraintLayout.LayoutParams(dp2px(240), dp2px(152))
            scaleType = ImageView.ScaleType.FIT_CENTER
        }
        rootLayout.addView(ivFlag)
    }
    private fun initHelloTextView() {
        tvHello = TextView(this).apply {
            id = View.generateViewId()
            layoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            text = getString(R.string.textview)
            textSize = 20f
        }
        rootLayout.addView(tvHello)
    }
    private fun initClickButton() {
        btnClick = Button(this).apply {
            id = View.generateViewId()
            layoutParams = ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
            text = getString(R.string.button)
        }
        rootLayout.addView(btnClick)
    }


    /**
     * 使用 ConstraintSet 设置控件的约束（位置关系）
     * 实现：国旗在上半部分居中，文本在屏幕正中，按钮在下半部分居中
     */
    /**
     * 使用 ConstraintSet 设置控件的约束（位置关系）
     * 【最终修正】实现：国旗在上半部分居中，文本在屏幕正中，按钮在下半部分居中
     */
    private fun setViewConstraints() {
        val constraintSet = ConstraintSet()
        constraintSet.clone(rootLayout)

        // 1. 创建两条水平 Guideline（控制垂直位置）
        // 国旗的 Guideline：屏幕高度 25% 处
        val guidelineFlagId = View.generateViewId()
        constraintSet.create(guidelineFlagId, ConstraintSet.HORIZONTAL_GUIDELINE)
        constraintSet.setGuidelinePercent(guidelineFlagId, 0.25f)

        // 按钮的 Guideline：屏幕高度 75% 处
        val guidelineBtnId = View.generateViewId()
        constraintSet.create(guidelineBtnId, ConstraintSet.HORIZONTAL_GUIDELINE)
        constraintSet.setGuidelinePercent(guidelineBtnId, 0.75f)


        // 2. 约束国旗：垂直中心与 25% Guideline 对齐 + 水平居中
        constraintSet.centerVertically(ivFlag.id, guidelineFlagId)
        constraintSet.centerHorizontally(ivFlag.id, ConstraintSet.PARENT_ID)

        // 3. 约束文本：垂直中心与父布局对齐 + 水平居中
        constraintSet.centerVertically(tvHello.id, ConstraintSet.PARENT_ID)
        constraintSet.centerHorizontally(tvHello.id, ConstraintSet.PARENT_ID)

        // 4. 约束按钮：垂直中心与 75% Guideline 对齐 + 水平居中
        constraintSet.centerVertically(btnClick.id, guidelineBtnId)
        constraintSet.centerHorizontally(btnClick.id, ConstraintSet.PARENT_ID)


        // 应用所有约束
        constraintSet.applyTo(rootLayout)
    }
    private fun handleWindowInsets() {
        ViewCompat.setOnApplyWindowInsetsListener(rootLayout) { view, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            view.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
    }

    private fun setButtonClickListener() {
        btnClick.setOnClickListener {
            tvHello.text = getString(R.string.clicked)
        }
    }
    private fun setFlagByLanguage() {
        ivFlag.setImageResource(R.drawable.flag)
    }
    private fun dp2px(dp: Int): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dp.toFloat(),
            resources.displayMetrics
        ).toInt()
    }
}